package com.example.demo.controller;

import com.example.demo.entity.Chapter;
import com.example.demo.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;

@RestController
@RequestMapping("/api/chapters")
public class ChapterController {

    @Autowired
    private ChapterService chapterService;

    // POST /api/chapters
    // 创建新章节
    @PostMapping
    public ResponseEntity<?> createChapter(@RequestBody Chapter chapter) {
        try {
            Chapter newChapter = chapterService.createChapter(chapter);
            // 返回创建成功的章节对象，其中包含自增的 chapterId
            return new ResponseEntity<>(newChapter, HttpStatus.CREATED);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage()); // 400 Bad Request
        } catch (RuntimeException e) {
            // 捕获可能的外键约束失败等错误
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("章节创建失败: " + e.getMessage());
        }
    }

    // GET /api/chapters/{id}
    // 根据章节 ID 获取单个章节
    @GetMapping("/{id}")
    public ResponseEntity<Chapter> getChapterById(@PathVariable("id") Integer chapterId) {
        return chapterService.findChapterById(chapterId)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build()); // 404 Not Found
    }

    // GET /api/chapters/course/{courseId}
    // 获取某一课程下的所有章节（按顺序）
    @GetMapping("/course/{courseId}")
    public List<Chapter> getChaptersByCourseId(@PathVariable("courseId") String courseId) {
        return chapterService.findChaptersByCourseId(courseId);
    }

    // PUT /api/chapters/{id}
    @PutMapping("/{id}")
    public ResponseEntity<?> updateChapter(@PathVariable("id") Integer chapterId, @RequestBody Chapter chapterDetails) {
        chapterDetails.setChapterId(chapterId); // 确保更新的是路径中的 ID

        if (chapterService.updateChapter(chapterDetails)) {
            return ResponseEntity.ok("章节信息更新成功");
        } else {
            return ResponseEntity.notFound().build(); // 404 Not Found (原章节不存在)
        }
    }

    // DELETE /api/chapters/{id}
    // 删除章节
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteChapter(@PathVariable("id") Integer chapterId) {
        if (chapterService.deleteChapter(chapterId)) {
            return ResponseEntity.noContent().build(); // 204 No Content
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}